package au.com.betaversion;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import au.com.betaversion.domain.Aircraft;
import au.com.betaversion.domain.AircraftApiLog;
import au.com.betaversion.domain.DatabaseInfo;
import au.com.betaversion.repository.AircraftApiLogRepository;
import au.com.betaversion.repository.AircraftRepository;
import au.com.betaversion.repository.PhotoRepository;

@Controller
@RequestMapping("/api")
public class ApiController {
	
	private static final String ACTIVE_RESPONSE = "pong";
	
	@Autowired
	private AircraftRepository aircraftRepository;
	
	@Autowired
	private PhotoRepository photoRepository;
	
	@Autowired
	private AircraftApiLogRepository aircraftApiLogRepository;
	
	@RequestMapping("/aircraft")
	public @ResponseBody DatabaseInfo getDatabaseInfo() {
		DatabaseInfo databaseInfo = new DatabaseInfo();
		databaseInfo.setAircraftCount(aircraftRepository.count());
		return databaseInfo;
	}
	
	@RequestMapping("/aircraft/{id}")
	public @ResponseBody Aircraft getAircraftDetailes(@PathVariable("id") String id,
			HttpServletRequest request) {
		return aircraftRepository.findOne(id.toUpperCase());
	}
	
	@RequestMapping("/aircraft/log")
	public String getAircraftLogs(Model model) {
		List<AircraftApiLog> aircraftApiLogs = aircraftApiLogRepository.findAll();

		Collections.sort(aircraftApiLogs, new Comparator<AircraftApiLog>() {
			@Override
			public int compare(AircraftApiLog o1, AircraftApiLog o2) {
				return o2.getDate().compareTo(o1.getDate());
			}
		});

		model.addAttribute("logs", aircraftApiLogs);
		return "api-aircraft-logs";
	}

	@RequestMapping("/ping")
	public @ResponseBody String getPingPong() {
		return ACTIVE_RESPONSE;
	}

}
